package com.moco.launcher.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.moco.launcher.R;
import com.moco.launcher.bean.PickItemInfo;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Paint.Style;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

/**
 * ����ѡ����
 * ��������http://blog.csdn.net/zhongkejingwang/article/details/38513301
 * 
 * @author chenjing
 * 
 */
public class WheelView extends View {

	public static final String TAG = "PickerView";
	/**
	 * text之间间距和minTextSize之比
	 */
	public static final float MARGIN_ALPHA = 2.2f;// 2.8f;
	/**
	 * 自动回滚到中间的速度
	 */
	public static final float SPEED = 1;

	private List<PickItemInfo> mDataList;
	/**
	 * 选中的位置，这个位置是mDataList的中心位置，一直不变
	 */
	private int mCurrentSelected;
	private Paint mPaint;

	private float mMaxTextSize = 160;
	private float mMinTextSize = 80;

	private float mMaxTextAlpha = 255;
	private float mMinTextAlpha = 120;
	private float mMarginWidth = 0;

	private int mColorText = 0xFFFFFFF;

	private int mViewHeight;
	private int mViewWidth;

	private float mLastDownY;
	private Context mContext = null;
	/**
	 * 滑动的距离
	 */
	private float mMoveLen = 0;
	private boolean isInit = false;
	private onSelectListener mSelectListener;
	private Timer timer;
	private MyTimerTask mTask;
	UiParam mHlParam = new UiParam();

	Handler updateHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (Math.abs(mMoveLen) < SPEED) {
				mMoveLen = 0;
				if (mSelectListener != null) {
					mSelectListener.onStop(getCurrentSelectId());
				}
				if (mTask != null) {
					mTask.cancel();
					mTask = null;
				}
			} else
				// 这里mMoveLen / Math.abs(mMoveLen)是为了保有mMoveLen的正负号，以实现上滚或下滚
				mMoveLen = mMoveLen - mMoveLen / Math.abs(mMoveLen) * SPEED;
			invalidate();
		}
	};

	public WheelView(Context context) {
		super(context);
		init();
	}

	public WheelView(Context context, AttributeSet attrs) {
		super(context, attrs);

		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.PickerView);
		mMarginWidth = a.getDimension(R.styleable.PickerView_margin_width, 0);
		a.recycle();
		mContext = context;
		init();
	}

	public void setOnSelectListener(onSelectListener listener) {
		mSelectListener = listener;
	}

	private void performSelect() {
		if (mSelectListener != null)
			mSelectListener.onSelect(mDataList.get(mCurrentSelected).getId());
	}

	public String getCurrentSelectId() {
		if (mDataList.size() == 0)
			return "";

		return mDataList.get(mCurrentSelected).getId();
	}

	public String getCurrentSelectText() {
		if (mDataList.size() == 0)
			return "";

		return mDataList.get(mCurrentSelected).getText();
	}

	public void setData(List<PickItemInfo> datas) {
		mDataList = datas;
		mCurrentSelected = datas.size() / 2;
	}

	public void setSelected(int selected) {
		mCurrentSelected = selected;
	}

	private void moveHeadToTail() {
		PickItemInfo head = mDataList.get(0);
		mDataList.remove(0);
		mDataList.add(head);
	}

	private void moveTailToHead() {
		PickItemInfo tail = mDataList.get(mDataList.size() - 1);
		mDataList.remove(mDataList.size() - 1);
		mDataList.add(0, tail);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		mViewHeight = getMeasuredHeight();
		mViewWidth = getMeasuredWidth();
		// 按照View的高度计算字体大小
		mMaxTextSize = mViewHeight / 4.0f;
		mMinTextSize = mMaxTextSize / 2.0f;
		isInit = true;
		invalidate();
	}

	private void init() {
		timer = new Timer();
		mDataList = new ArrayList<PickItemInfo>();
		mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mPaint.setStyle(Style.FILL);
		mPaint.setTextAlign(Align.CENTER);
		mPaint.setColor(mColorText);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		Log.d(TAG, "isInit" + isInit);
		// 根据index绘制view
		if (isInit)
			drawData(canvas);
	}

	private void drawSelected(Canvas canvas) {
		// 先绘制选中的text再往上往下绘制其余的text
		float scale = parabola(mViewHeight / 4.0f, mMoveLen);
		mMarginWidth = 0;
		float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;
		mPaint.setTextSize(size / 1);
		if (this.mSelectListener != null) {
			if (this.mSelectListener.onRelayout(getCurrentSelectId(), mHlParam)) {
				mMarginWidth = mHlParam.nMarginWidth;
				Log.d(TAG, "COLOR= " + mHlParam.HlColor);
				mPaint.setColor(mHlParam.HlColor);
			}
			// mPaint.setTextSize(size/3);
		}

		mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));

		// text居中绘制，注意baseline的计算才能达到居中，y值是text中心坐标
		float x = (float) (mViewWidth / 2.0);
		float y = (float) (mViewHeight / 2.0 + mMoveLen);
		FontMetricsInt fmi = mPaint.getFontMetricsInt();
		float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));

		PickItemInfo item = mDataList.get(mCurrentSelected);
		String text = item.getText();

		if (item.getBackIconId() != -1) {
			Bitmap bm = BitmapFactory.decodeResource(getResources(),
					item.getBackIconId());
			float x1 = (mViewWidth / 2 - bm.getWidth() / 2);
			float y1 = (float) (mViewHeight / 2.0 - bm.getHeight() / 2.0 + mMoveLen);
			canvas.drawBitmap(bm, x1, y1, mPaint);

			bm = BitmapFactory.decodeResource(getResources(),
					item.getLeftIconLight());
			x1 = mViewWidth / 8;
			y1 = (float) (mViewHeight / 2.0 - bm.getHeight() / 2.0 + mMoveLen);
			canvas.drawBitmap(bm, x1, y1, mPaint);
		}

		/*
		 * Log.d(TAG, "mMoveLen = " + mMoveLen); Log.d(TAG, "mViewHeight = " +
		 * mViewHeight); Log.d(TAG, "mViewWidth = " + mViewWidth); Log.d(TAG,
		 * "mMaxTextSize = " + mMaxTextSize); Log.d(TAG, "mMinTextSize = " +
		 * mMinTextSize); Log.d(TAG, "MARGIN_ALPHA = " + MARGIN_ALPHA);
		 * Log.d(TAG, "scale = " + scale); Log.d(TAG, "size = " + size);
		 * Log.d(TAG, "x = " + x); Log.d(TAG, "baseline = " + baseline);
		 * Log.d(TAG, "text = " + text); Log.d(TAG, "\n\n");
		 */

		Log.d(TAG, "mMarginWidth = " + mMarginWidth);
		canvas.drawText(text, x - mMarginWidth, baseline, mPaint);

	}

	private void drawData(Canvas canvas) {
		Log.d(TAG, "mDataList SIZE =" + mDataList.size());
		if (this.mDataList.size() == 0)
			return;

		drawSelected(canvas);

		for (int i = 1; (mCurrentSelected - i) >= 0; i++) {
			drawOtherText(canvas, i, -1);
		}

		for (int i = 1; (mCurrentSelected + i) < mDataList.size(); i++) {
			drawOtherText(canvas, i, 1);
		}
	}

	/**
	 * @param canvas
	 * @param position
	 *            ����mCurrentSelected�Ĳ�ֵ
	 * @param type
	 *            1��ʾ���»��ƣ�-1��ʾ���ϻ���
	 */
	private void drawOtherText(Canvas canvas, int position, int type) {
		float d = (float) (MARGIN_ALPHA * mMinTextSize * position + type
				* mMoveLen);

		/*
		 * Log.d(TAG, "d = " + d); Log.d(TAG, "mViewHeight = " + mViewHeight);
		 * Log.d(TAG, "mMaxTextSize = " + mMaxTextSize); Log.d(TAG,
		 * "mMinTextSize = " + mMinTextSize); Log.d(TAG, "MARGIN_ALPHA = " +
		 * MARGIN_ALPHA);
		 */

		float scale = parabola(mViewHeight / 2.0f, d);
		float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;

		/*
		 * Log.d(TAG, "scale = " + scale); Log.d(TAG, "size = " + size);
		 */

		mPaint.setColor(mHlParam.Color);
		mPaint.setTextSize(size / 2);
		mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));

		float internal = mMinTextSize / 2
				* (mCurrentSelected + type * position) / mCurrentSelected;

		float d2 = (float) (MARGIN_ALPHA * mMinTextSize * position + internal + type
				* mMoveLen);

		float y = (float) (mViewHeight / 2.0 + type * d2);

		/*
		 * Log.d(TAG, "internal " + internal); Log.d(TAG, "y " + y);
		 */

		FontMetricsInt fmi = mPaint.getFontMetricsInt();
		float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));

		PickItemInfo item = mDataList.get(mCurrentSelected + type * position);
		String text = item.getText();
		/*
		 * Log.d(TAG, "text = " + text); Log.d(TAG, "\n\n");
		 */
		float x = 0.0f;
		if (item.getLeftIconDark() != -1) {
			Bitmap bm = BitmapFactory.decodeResource(getResources(),
					item.getLeftIconDark());
			float x1 = mViewWidth / 8;
			float y1 = (float) (y - bm.getHeight() / 2.0 + mMoveLen);
			canvas.drawBitmap(bm, x1, y1, mPaint);
		}

		canvas.drawText(text, (float) (mViewWidth / 2.0), baseline, mPaint);
	}

	/**
	 * ������
	 * 
	 * @param zero
	 *            ������
	 * @param x
	 *            ƫ����
	 * @return scale
	 */
	private float parabola(float zero, float x) {
		float f = (float) (1 - Math.pow(x / zero, 2));
		return f < 0 ? 0 : f;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getActionMasked()) {
		case MotionEvent.ACTION_DOWN:
			doDown(event);
			break;
		case MotionEvent.ACTION_MOVE:
			doMove(event);
			break;
		case MotionEvent.ACTION_UP:
			doUp(event);
			break;
		}

		if ((event.getY() < (this.getHeight() / 2 - this.mMaxTextSize / 2))
				|| (event.getY() > this.getHeight() / 2 + this.mMaxTextSize / 2))
			return true;

		return super.onTouchEvent(event);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		Log.d(TAG, "onKeyDown");
		return true;
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {

		Log.d(TAG, "onKeyUp");
		return true;
	}

	private void doDown(MotionEvent event) {
		if (mTask != null) {
			mTask.cancel();
			mTask = null;
		}
		mLastDownY = event.getY();
	}

	private void doMove(MotionEvent event) {
		if (this.mDataList.size() == 0)
			return;
		mMoveLen += (event.getY() - mLastDownY);

		if (mMoveLen > MARGIN_ALPHA * mMinTextSize / 2) {
			// ���»������뿪����
			moveTailToHead();
			mMoveLen = mMoveLen - MARGIN_ALPHA * mMinTextSize;
		} else if (mMoveLen < -MARGIN_ALPHA * mMinTextSize / 2) {
			// ���ϻ������뿪����
			moveHeadToTail();
			mMoveLen = mMoveLen + MARGIN_ALPHA * mMinTextSize;
		}

		mLastDownY = event.getY();
		PickItemInfo item = mDataList.get(mCurrentSelected);
		invalidate();
	}

	private void doUp(MotionEvent event) {
		// ̧���ֺ�mCurrentSelected��λ���ɵ�ǰλ��move���м�ѡ��λ��
		if (Math.abs(mMoveLen) < 0.0001) {
			mMoveLen = 0;
			return;
		}
		if (mTask != null) {
			mTask.cancel();
			mTask = null;
		}
		mTask = new MyTimerTask(updateHandler);
		timer.schedule(mTask, 0, 10);
	}

	class MyTimerTask extends TimerTask {
		Handler handler;

		public MyTimerTask(Handler handler) {
			this.handler = handler;
		}

		@Override
		public void run() {
			handler.sendMessage(handler.obtainMessage());
		}
	}

	public class UiParam {
		public int Color = 0xFFFFFFF;
		public int HlColor = 0xFFFFFFF;
		public float nMarginWidth = 0;
	}

	public interface onSelectListener {
		boolean onRelayout(String nSelectId, UiParam param);

		boolean onSelect(String nSelectId);

		boolean onStop(String nSelectId);
	}
}
